import 'package:aichat_flutter_wallet/module/module_dapp/provider/dapp_page_provider.dart';
import 'package:aichat_flutter_wallet/module/module_dapp/provider/dapp_provider.dart';
import 'package:aichat_flutter_wallet/module/module_dapp/widgets/components/dapp_banner_comp.dart';
import 'package:aichat_flutter_wallet/module/module_dapp/widgets/components/dapp_favorite_comp.dart';

import 'package:aichat_flutter_wallet/module/module_dapp/widgets/components/dapp_list_page.dart';
import 'package:aichat_flutter_wallet/module/module_dapp/widgets/dapp_title.dart';
import 'package:aichat_flutter_wallet/module/module_dapp/widgets/components/coordinator_tab_layout.dart';

import 'package:aichat_flutter_wallet/module_common/utils/colors.dart';
import 'package:aichat_flutter_wallet/module_common/utils/task_code_to_flutter.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/header/page_header.dart';
import 'package:shimmer/shimmer.dart';

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import '../../../module_common/bridge/native_channel_bridge.dart';
import '../../../module_common/router/routers.dart';
import '../widgets/components/dapp_hot_comp.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import 'dapp_history_page.dart';

/// A Calculator.
class DappPage extends StatefulWidget {
  late String uri;
  DappPage({super.key, this.uri = ''});

  @override
  State<DappPage> createState() => DappPageState();
}

class DappPageState extends State<DappPage> {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      //  app 原生断 有传 这个 参数 情况下
      if (widget.uri.isNotEmpty) {
        TaskCodeToFlutter.linkToDAppLink(widget.uri);
        widget.uri = '';
      }
    });
  }
  initPage(String params){
    if (params.isNotEmpty) {
      TaskCodeToFlutter.linkToDAppLink(params);
    }
  }


  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }

  @override
  void dispose() {
    /// 取消路由订阅
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Container(
      child: Container(
        color: AppColors.c_white,
        child: Stack(
          children: [DAppContainer()],
        ),
      ),
    ));
  }
}

class DAppContainer extends StatefulWidget {
  const DAppContainer({super.key});

  @override
  State<DAppContainer> createState() => _DAppContainerState();
}

class _DAppContainerState extends State<DAppContainer>{
  @override
  void initState() {
    super.initState();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }

  @override
  void dispose() {
    /// 取消路由订阅
    // AppRouterPageUtils().routeObserver.unsubscribe(this);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // double statusBarHeight = MediaQuery.of(context).padding.top;
    return Scaffold(
        backgroundColor: Colors.white,
        appBar: PageHeaderCom(
          title: 'DApp',
          showBottomBorder: false,
          definedGoBack: true,
          goBack: () {
            NativeChannelBridge.instance.closeFlutterPage(num: 1);
          },
        ),
        body: Consumer<DAppProvider>(builder: (c, model, topWidget) {
          return Container(
            margin: EdgeInsets.only(bottom: 0),
            color: Colors.white,
            child: Column(
              children: [
                topWidget!,
                Expanded(
                    child: RefreshIndicator(
                        notificationPredicate: (notifation) {
                          // 返回true即可,避免下拉刷新时和NestedScrollView滑动冲突
                          return true;
                        },
                        onRefresh: () async {
                          await model.reloadData();
                        },
                        child: CoordinatorTabLayout(
                            onScrollTopListen: Provider.of<DAppPageProvider>(
                                    context,
                                    listen: false)
                                .listenScrollSetNum,
                            tabBarTitleWidget: Container(
                              margin: EdgeInsets.only(bottom: 10),
                              child: DAppTitle(
                                title: 'DApps',
                                isLoading: model.isLoading,
                              ),
                            ),
                            titles: model.dappsNameList.map((e) {
                              return e;
                            }).toList(growable: false),
                            headerView: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                SizedBox(
                                  height: 13.w,
                                ),
                                DAppBannerComp(),
                                // if (!model.isBannerLoading) DAppNoticeComp(),
                                DAppHotComp(),
                                DAppFavoriteComp(),
                                Container(
                                  width: double.infinity,
                                  color: const Color.fromRGBO(246, 246, 246, 1),
                                  height: 10.w,
                                ),
                              ],
                            ),
                            pages: model.dappsList.map((element) {
                              return DAppListPage(
                                list: element.children ?? [],
                                hasMore: true,
                              );
                            }).toList(growable: false)))),
              ],
            ),
          );
        }, child: Consumer2<DAppProvider, DAppPageProvider>(
            builder: (c, model, model2, child) {
          return SizedBox(
            child: Container(
              color: Colors.white,
              // color: model2.scrollNum > 0 ? Colors.white : Colors.transparent,
              padding: EdgeInsets.only(top: 0, left: 0, right: 0, bottom: 4.w),
              // height: statusBarHeight + 20 + 40 + 2,
              child: Column(
                children: [
                  if (!model.isBannerLoading)
                    GestureDetector(
                      onTap: () {
                        // Routes.router!.navigateTo(context, Routes.dAppHistoryRoute);
                        Navigator.of(context).push(
                          MaterialPageRoute(
                              builder: (_) {
                                return DAppHistoryPage();
                              },
                              settings:
                                  RouteSettings(name: Routes.dAppHistoryRoute)),
                        );
                      },
                      child: Container(
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(8.w),
                            color: Color.fromRGBO(244, 244, 244, 1)
                            // color: model2.scrollNum > 0
                            //     ? Color.fromRGBO(244, 244, 244, 1)
                            //     : Colors.white,
                            ),
                        height: 40.w,
                        margin: EdgeInsets.only(left: 20.w, right: 20.w),
                        padding: EdgeInsets.only(
                            left: 15.w, top: 10.w, right: 15.w, bottom: 10.w),
                        child: Row(
                          children: [
                            Container(
                              margin: EdgeInsets.only(right: 5.w),
                              child: Image.asset(
                                'assets/images/dapp/search.png',
                                width: 20.w,
                                height: 20.w,
                              ),
                            ),
                            Expanded(
                              flex: 1,
                              child: Text(
                                'Search or type URL',
                                style: TextStyle(
                                    color: model2.scrollNum > 0
                                        ? Color.fromRGBO(191, 190, 203, 1)
                                        : Color.fromRGBO(190, 189, 202, 1)),
                              ),
                            )
                          ],
                        ),
                      ),
                    ),
                  if (model.isBannerLoading)
                    Shimmer.fromColors(
                        baseColor: Color.fromRGBO(246, 246, 246, 1),
                        highlightColor: Colors.grey.shade300,
                        child: Container(
                          height: 40.w,
                          margin: const EdgeInsets.only(left: 20, right: 20),
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(4),
                            color: Colors.grey,
                          ),
                        ))
                ],
              ),
            ),
          );
        })));
  }
}
